package com.googlecode.continuity.plugin.project.server.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.context.SecurityContextHolder;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
import com.googlecode.continuity.core.client.Group;
import com.googlecode.continuity.core.server.mvc.ContinuityModel;
import com.googlecode.continuity.core.server.security.SecurityUserToken;
import com.googlecode.continuity.plugin.project.client.Project;
import com.googlecode.continuity.plugin.project.server.service.ProjectService;

/**
 * ProjectEditController
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class ProjectEditController extends SimpleFormController {
// ------------------------------ FIELDS ------------------------------

  private static final String PROJECT_ATTRIBUTE = "project";

  private ProjectService projectService;
  private String viewURL;
  private String listURL;

// --------------------- GETTER / SETTER METHODS ---------------------

  public String getListURL() {
    return listURL;
  }

  public void setListURL(String listURL) {
    this.listURL = listURL;
  }

  public String getViewURL() {
    return viewURL;
  }

  public void setViewURL(String viewURL) {
    this.viewURL = viewURL;
  }

  public void setProjectService(ProjectService projectService) {
    this.projectService = projectService;
  }

// -------------------------- OTHER METHODS --------------------------

  protected Object formBackingObject(HttpServletRequest request) throws Exception {
    return request.getAttribute(PROJECT_ATTRIBUTE);
  }

  protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    if (!isFormSubmission(request)) {
      if (request.getRequestURI().contains("create")) {
        request.setAttribute(PROJECT_ATTRIBUTE, new Project());
      } else {
        int id = Integer.parseInt(request.getParameter("id"));
        Project project = projectService.getProjectByID(id);

        // if project doesn't exist show error and list mode
        // todo: include error
        if (project == null) {
          return new ModelAndView(new RedirectView(getListURL(), true));
        }
        request.setAttribute(PROJECT_ATTRIBUTE, project);
      }
    }

    return super.handleRequestInternal(request, response);
  }

  protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object o,
                                  BindException errors) throws Exception {
    Project project = (Project) o;
    if (request.getRequestURI().contains("create")) {
      Group members = new Group();
      members.setName(project.getName());
      members.addMember(
          ((SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser());
      project.setMembers(members);
    }

    projectService.storeProject(project);
    return new ModelAndView(new RedirectView(getViewURL(), true), "id", project.getId());
  }

  protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors,
                                  Map controlModel) throws Exception {
    return showForm(request, errors, getFormView(), new ContinuityModel());
  }
}
